// @flow
import React from 'react'
import styles from './BusinessFillter.css'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { Input, Row, Col, Button, Select } from 'antd'
import { connect } from 'react-redux'

const Option = Select.Option

type Props = {
  userId: string,
  getData: Function
}

type State = {
  deviceType: Array<Object>,
  owner: Array<Object>,
  status: Array<Object>,
  dataSource: Array<Object>
}

class Fillter extends React.Component {
  props: Props
  state: State
  searchQuery: string
  searchInfo: Object
  handleDeviceName: Function
  handleSearch: Function
  handleDeviceType: Function
  handleOwner: Function
  handleSource: Function
  handleStatus: Function
  addAllItem: boolean
  constructor (props: Object) {
    super(props)
    this.addAllItem = true
    this.state = {
      dataSource: [],
      deviceType: [{ value: '全部' }],
      owner: [{ id: 0, name: '全部' }],
      status: [{ id: 0, value: '全部' }]
    }
    this.handleDeviceName = this.handleDeviceName.bind(this)
    this.handleSearch = this.handleSearch.bind(this)
    this.handleDeviceType = this.handleDeviceType.bind(this)
    this.handleStatus = this.handleStatus.bind(this)
    this.handleOwner = this.handleOwner.bind(this)
    this.handleSource = this.handleSource.bind(this)
    this.handleSearch = this.handleSearch.bind(this)
    this.searchInfo = {}
  }
  componentDidMount () {
    this.getFillterDatas(`${__SERVICE_API__}sys/dicts?type=deviceStatus`, 'status')
    this.getFillterDatas(`${__SERVICE_API__}device/customers?userId=${this.props.userId}&pageSize=200000`, 'owner')
    // this.getFillterDatas(`${__SERVICE_API__}device/dicts/device-types`, 'deviceType')

  //  ${__SERVICE_API__}sys/dicts?type=industry   行业
    const types = ['dataSource']
  // $FlowFixMe
    universalFetch(`${__SERVICE_API__}device/conditions?types=${types}`)
    .then(res => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        dataSource: json.result.dataSource
      })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }
  getFillterDatas (url: string, name: string) {
    universalFetch(url)
    .then(res => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      let data = this.state[name]
      data.push(...json.result)
      this.setState({ [name]: data })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }
  handleSearch () {
    let { deviceName, deviceType, owner, status, dataSource } = this.searchInfo
    //  不确定是否有值,没有则设置为空
    deviceName = deviceName || ''
    deviceType = deviceType || ''
    owner = owner || ''
    status = status || ''
    dataSource = dataSource || ''
    let searchQuery = `&name=${deviceName}&type=${deviceType}&status=${status}&customerId=${owner}&dataSource=${dataSource}`
    this.props.getData(1, 20, searchQuery)
  }
  handleDeviceName (e: any) {
    this.searchInfo.deviceName = e.target.value
  }
  handleDeviceType (value: any) {
    if (value === '全部') {
      this.searchInfo.deviceType = ''
      return
    }
    this.searchInfo.deviceType = value
  }
  handleOwner (value: any) {
    if (value === 0) {
      this.searchInfo.owner = ''
      return
    }
    this.searchInfo.owner = value
  }
  handleStatus (value: any) {
    if (value === '全部') {
      this.searchInfo.status = ''
      return
    }
    this.searchInfo.status = value
  }
  handleSource (value: any) {
    if (value === '全部') {
      this.searchInfo.dataSource = ''
      return
    }
    this.searchInfo.dataSource = value
  }

  render () {
    const { owner, status, dataSource } = this.state

    return (
      <div className={styles['searchBox']}>
        <Row gutter={24} justify='center'>
          <Col className={styles['ant-col-2']} span={1}>
            <div className='gutter-box'>
              <Input placeholder='设备名称' onInput={this.handleDeviceName} onPressEnter={this.handleSearch} />
            </div>
          </Col>
          {
            // <Col className={styles['ant-col-2']} span={2}>
            //   <div className='gutter-box'>
            //     <Select
            //       showSearch
            //       placeholder='设备类型'
            //       optionFilterProp='children'
            //       filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            //       className={styles['selctBox']}
            //       onSelect={this.handleDeviceType}
            //    >
            //       {deviceType.map((item, index) => {
            //         return <Option value={item.value} key={index + 'deviceType'}
            //           className={styles['optionBox']}>{item.value}</Option>
            //       })}
            //     </Select>
            //   </div>
            // </Col>
          }
          <Col className={styles['ant-col-2']} span={1}>
            <div className='gutter-box'>
              <Select
                showSearch
                placeholder='设备状态'
                optionFilterProp='children'
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                className={styles['selctBox']}
                onSelect={this.handleStatus}
             >
                {status.map((item, index) => {
                  return <Option value={item.value} key={index + 'status'}
                    className={styles['optionBox']}>{item.value}</Option>
                })}
              </Select>
            </div>
          </Col>
          <Col className={styles['ant-col-3']} span={1}>
            <div className='gutter-box'>
              <Select
                showSearch
                placeholder='客户'
                optionFilterProp='children'
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                className={styles['selctBox']}
                onSelect={this.handleOwner}
                >
                {owner.map((item, index) => {
                  return <Option value={item.id} key={index + 'owner'}
                    className={styles['optionBox']}>{item.name}</Option>
                })}
              </Select>
            </div>
          </Col>
          <Col className={styles['ant-col-2']} span={1}>
            <div className='gutter-box'>
              <Select
                showSearch
                placeholder='数据源'
                optionFilterProp='children'
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                className={styles['selctBox']}
                onSelect={this.handleSource}
                >
                <Option value=''>
                  全部
                </Option>
                {
                  dataSource.map((item, i) => {
                    return <Option key={i} value={item.value}>
                      {item.label}
                    </Option>
                  })
                }
              </Select>
            </div>
          </Col>
          <Button icon='search' onClick={this.handleSearch} />
        </Row>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Fillter)
